package com.easychat.service.impl;


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.easychat.config.Appconfig;
import com.easychat.entity.UserInfo;
import com.easychat.entity.UserInfoBeauty;
import com.easychat.entity.constants.Constants;
import com.easychat.entity.dto.TokenUserInfoDto;
import com.easychat.entity.enums.BeautyAccountStatusEnum;
import com.easychat.entity.enums.JoinTypeEnum;
import com.easychat.entity.enums.UserContactTypeEnum;
import com.easychat.entity.enums.UserStatusEnum;
import com.easychat.entity.vo.UserInfoVo;
import com.easychat.exception.BusinessException;
import com.easychat.mapper.UserInfoBeautyMapper;
import com.easychat.mapper.UserInfoMapper;
import com.easychat.redis.RedisComponent;
import com.easychat.service.UserInfoService;
import com.easychat.utils.CopyTools;
import com.easychat.utils.StringTools;
import com.sun.org.apache.bcel.internal.generic.ARETURN;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kyle.li
 * @version 1.0
 * @description: TODO
 * @date 2024/6/29 22:56
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoBeautyMapper userInfoBeautyMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private Appconfig appconfig;

    @Resource
    private RedisComponent redisComponent;
    /**
     * 注册
     * @param email
     * @param nickName
     * @param password
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(String email, String nickName, String password) {
        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = userInfoMapper.selectByEmail(email);

        if(null != userInfo) {
            throw new BusinessException("邮箱账号已经存在");
        }

        String userId = StringTools.getUserId();
        UserInfoBeauty beautyAccount = userInfoBeautyMapper.selectByEmail(email);
        //靓号未使用
        boolean useBeautyAccount = null != beautyAccount && BeautyAccountStatusEnum.NO_USER.getStatus().equals(beautyAccount.getStatus());
        //靓号赋值
        if (useBeautyAccount){
            userId = UserContactTypeEnum.USER.getPrefix() + beautyAccount.getUserId();
        }

        Date curDate = new Date();
        userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setNickName(nickName);
        userInfo.setEmail(email);
        userInfo.setPassword(StringTools.encodeMd5(password));
        userInfo.setCreateTime(curDate);
        userInfo.setStatus(UserStatusEnum.ENABLE.getStatus());
        userInfo.setLastOffTime(curDate.getTime());
        userInfo.setJoinType(JoinTypeEnum.APPLY.getType());
        userInfoMapper.insert(userInfo);

        if(useBeautyAccount){
            UserInfoBeauty updateBeauty = new UserInfoBeauty();
            updateBeauty.setStatus(BeautyAccountStatusEnum.USEED.getStatus());
            userInfoBeautyMapper.updateById(updateBeauty, beautyAccount.getUserId());
        }
        //TODO 创建机器人好友
    }

    //登录
    @Override
    public UserInfoVo login(String email, String password) {
        UserInfo userInfo = userInfoMapper.selectByEmail(email);
        if(null == userInfo || userInfo.getPassword().equals(password)){
            throw new BusinessException("账号或者密码不存在");
        }

        //TODO 查询我的群组
        //TODO 查询我的联系人

        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto(userInfo);

        //从redis中，获取用户心跳
        Long userHeartBeat = redisComponent.getUserHeartBeat(userInfo.getUserId());
        if(userHeartBeat != null){
            throw new BusinessException("此账号已经在别处登录，请退出后再登录");
        }

        //保存登录信息到 redis 中
        String token = StringTools.encodeMd5(tokenUserInfoDto.getUserId() + StringTools.getRandomString(Constants.Length_20));
        tokenUserInfoDto.setToken(token);
        redisComponent.saveTokenUserInfoDto(tokenUserInfoDto);

        UserInfoVo userInfoVo = CopyTools.copyEntity(userInfo, UserInfoVo.class);
        userInfoVo.setToken(tokenUserInfoDto.getToken());
        userInfoVo.setAdmin(tokenUserInfoDto.getAdmin());

        return userInfoVo;
    }

    /**
     * 返回登录信息给页面
     * @param userInfo
     * @return TokenUserInfoDto
     */
    private TokenUserInfoDto getTokenUserInfoDto(UserInfo userInfo){
        TokenUserInfoDto tokenUserInfoDto = new TokenUserInfoDto();
        tokenUserInfoDto.setUserId(userInfo.getUserId());
        tokenUserInfoDto.setNickName(userInfo.getNickName());

        String adminEmails = appconfig.getAdminEmails();
        if(StrUtil.isNotEmpty(adminEmails) && ArrayUtil.contains(adminEmails.split(","), userInfo.getEmail())){
            tokenUserInfoDto.setAdmin(true);
        }else {
            tokenUserInfoDto.setAdmin(false);
        }
        return tokenUserInfoDto;
    }
}
